package com.google.code.swingonfire.component.foldable;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;

import javax.swing.JComponent;

public abstract class AbstractJFoldableTrigger extends JComponent implements FoldableListener, PropertyChangeListener
{

    private static final long serialVersionUID = 5481940598740013725L;

    private static final Collection<String> NOTABLE_PROPERTY_CHANGES = new HashSet<String>(Arrays.asList("direction",
        "foldAutomatically", "triggerMoving", "triggerComponent", "triggerLocation"));

    private JFoldablePanel panel;
    private String actionCommand;

    public AbstractJFoldableTrigger()
    {
        super();
    }

    public JFoldablePanel getPanel()
    {
        return panel;
    }

    public void setPanel(JFoldablePanel panel)
    {
        if (this.panel != panel)
        {
            if (this.panel != null)
            {
                this.panel.removePropertyChangeListener(this);
                this.panel.removeFoldableListener(this);
            }

            this.panel = panel;

            if (this.panel != null)
            {
                this.panel.addPropertyChangeListener(this);
                this.panel.addFoldableListener(this);
            }
        }
    }

    public void addActionListener(ActionListener listener)
    {
        listenerList.add(ActionListener.class, listener);
    }

    public void removeActionListener(ActionListener listener)
    {
        listenerList.add(ActionListener.class, listener);
    }

    public String getActionCommand()
    {
        return actionCommand;
    }

    public void setActionCommand(String actionCommand)
    {
        this.actionCommand = actionCommand;
    }

    protected void fireActionPerformed()
    {
        Object[] listeners = listenerList.getListenerList();
        ActionEvent e = new ActionEvent(this, 0, actionCommand, System.currentTimeMillis(), 0);

        for (int i = listeners.length - 2; i >= 0; i -= 2)
        {
            if (listeners[i] == ActionListener.class)
            {
                ((ActionListener) listeners[i + 1]).actionPerformed(e);
            }
        }
    }

    @Override
    public void propertyChange(PropertyChangeEvent event)
    {
        if (NOTABLE_PROPERTY_CHANGES.contains(event.getPropertyName()))
        {
            updateLayout();
        }
    }

    protected abstract void updateLayout();

}
